extends Node2D

@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var key_tip: Node2D = $KeyTip
var is_player_entered: bool = false
@onready var door: Sprite2D = $Door
@onready var door_open_animation: AnimationPlayer = $DoorOpenAnimation
@onready var camera_move_target_point: Marker2D = $CameraMoveTargetPoint
var is_opened: bool = false


func show_key_tip():
	animation_player.stop()
	animation_player.play("key_tip")
	
	var tween = create_tween()
	tween.tween_property(key_tip, "modulate:a", 1.0, 0.3) \
	.set_trans(Tween.TRANS_CUBIC) \
	.set_ease(Tween.EASE_OUT).from_current()
	

func hide_key_tip():
	var tween = create_tween()
	tween.tween_property(key_tip, "modulate:a", 0.0, 0.3) \
	.set_trans(Tween.TRANS_CUBIC) \
	.set_ease(Tween.EASE_IN).from_current()


func _on_interact_area_body_entered(body: Node2D) -> void:
	is_player_entered = true
	show_key_tip()


func _on_interact_area_body_exited(body: Node2D) -> void:
	is_player_entered = false
	hide_key_tip()
	
	
func _process(delta: float) -> void:
	process_open_door()
	

func process_open_door():
	if Input.is_action_just_pressed("interact") and is_player_entered and GlobalData.player_data.big_key_num >= 5 and not is_opened:
		is_opened = true
		
		AudioManager.play_music("sfx_ocean")
		
		door_open_animation.play("door_open")
		
		var level = get_tree().current_scene as Level
		level.white_fade_effect.fade_in(on_fade_in_finish)
		
		# tween camera
		level.camera.is_following = false
		var tween = create_tween()
		tween.tween_property(level.camera, "zoom", Vector2(2.0, 2.0), 3.0).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
		
		tween = create_tween()
		tween.tween_property(level.camera, "position", camera_move_target_point.global_position, 3.0).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
		
		level.player.disable_hurt_collision()
		level.player.enable_input = false
	

func on_fade_in_finish():
	await get_tree().create_timer(1.0).timeout
	var level = get_tree().current_scene as Level
	level.on_game_finish()
	
